package com.lw.lost.activity.admin

import android.os.Bundle
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.lw.lost.adapters.ManagePostAdapter
import com.lw.lost.databinding.ActivityPostManageBinding
import com.lw.lost.db.DBlost
import com.lw.lost.models.Post

class PostManageActivity : AppCompatActivity() {

    private lateinit var binding: ActivityPostManageBinding
    private lateinit var db: DBlost
    private lateinit var postAdapter: ManagePostAdapter
    private var searchKeyword = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPostManageBinding.inflate(layoutInflater)
        setContentView(binding.root)

        setSupportActionBar(binding.toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.title = "帖子管理"

        db = DBlost(this)
        setupRecyclerView()
        setupSearchView()
        loadPosts()
    }

    private fun setupRecyclerView() {
        postAdapter = ManagePostAdapter(
            onPostClick = { post ->
                showPostDetailDialog(post)
            },
            onActionClick = { post ->
                showActionDialog(post)
            }
        )

        binding.recyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = postAdapter
            addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL))
        }
    }

    private fun setupSearchView() {
        binding.searchView.apply {
            queryHint = "输入内容搜索"
            isIconified = false
            
            setOnQueryTextListener(object : androidx.appcompat.widget.SearchView.OnQueryTextListener {
                override fun onQueryTextSubmit(query: String?): Boolean {
                    searchKeyword = query ?: ""
                    loadPosts()
                    return true
                }

                override fun onQueryTextChange(newText: String?): Boolean {
                    searchKeyword = newText ?: ""
                    loadPosts()
                    return true
                }
            })
        }
    }

    private fun loadPosts() {
        val cursor = if (searchKeyword.isEmpty()) {
            db.postDao.getAllPosts()
        } else {
            db.postDao.searchPosts(searchKeyword)
        }

        val posts = mutableListOf<Post>()
        cursor.use { cursor ->
            while (cursor.moveToNext()) {
                posts.add(
                    Post(
                        postId = cursor.getLong(cursor.getColumnIndexOrThrow("postId")),
                        userId = cursor.getLong(cursor.getColumnIndexOrThrow("userId")),
                        content = cursor.getString(cursor.getColumnIndexOrThrow("content")),
                        imageUrl = cursor.getString(cursor.getColumnIndexOrThrow("imageUrl")),
                        status = cursor.getInt(cursor.getColumnIndexOrThrow("status")),
                        createTime = cursor.getString(cursor.getColumnIndexOrThrow("createTime")),
                        likeCount = cursor.getInt(cursor.getColumnIndexOrThrow("likeCount")),
                        commentCount = cursor.getInt(cursor.getColumnIndexOrThrow("commentCount"))
                    )
                )
            }
        }

        postAdapter.submitList(posts)
        binding.tvEmpty.visibility = if (posts.isEmpty()) View.VISIBLE else View.GONE
    }

    private fun updateUI(posts: List<Post>) {
        postAdapter.submitList(posts)

        // 更新统计信息
        val normalPosts = posts.count { it.status == 0 }
        val deletedPosts = posts.count { it.status == 1 }
        binding.tvPostCount.text = "共 ${posts.size} 条帖子（正常: $normalPosts, 已删除: $deletedPosts）"

        // 更新空状态显示
        binding.tvEmpty.visibility = if (posts.isEmpty()) View.VISIBLE else View.GONE
        binding.recyclerView.visibility = if (posts.isEmpty()) View.GONE else View.VISIBLE
    }

    private fun showPostDetailDialog(post: Post) {
        // 获取发帖用户信息
        val userCursor = db.userDao.getUserById(post.userId)
        val username = if (userCursor.moveToFirst()) {
            "${userCursor.getString(userCursor.getColumnIndexOrThrow("name"))} (${userCursor.getString(userCursor.getColumnIndexOrThrow("username"))})"
        } else "未知用户"
        userCursor.close()

        AlertDialog.Builder(this)
            .setTitle("帖子详情")
            .setMessage("""
                发帖用户：$username
                发帖时间：${post.createTime}
                帖子内容：${post.content}
                帖子状态：${if (post.status == 0) "正常" else "已删除"}
                ${if (post.imageUrl != null) "\n图片地址：${post.imageUrl}" else ""}
            """.trimIndent())
            .setPositiveButton("确定", null)
            .show()
    }

    private fun showActionDialog(post: Post) {
        if (post.status == 1) {
            Toast.makeText(this, "该帖子已删除", Toast.LENGTH_SHORT).show()
            return
        }

        AlertDialog.Builder(this)
            .setTitle("删除帖子")
            .setMessage("确定要删除该帖子吗？")
            .setPositiveButton("确定") { _, _ ->
                deletePost(post.postId)
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun deletePost(postId: Long) {
        val result = db.postDao.updatePostStatus(postId, 1)
        if (result > 0) {
            Toast.makeText(this, "已删除帖子", Toast.LENGTH_SHORT).show()
            loadPosts()
        } else {
            Toast.makeText(this, "操作失败", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            finish()
            return true
        }
        return super.onOptionsItemSelected(item)
    }
} 